package collections;

import java.util.HashSet;

/**
 * Created by pc on 2015/1/20.
 * HashSet 不是线程安全的*
 * HashSet既判断equals又判断hashCode()
 */

class A {
    public boolean equals(Object x){ return true; }
}

class B{
    //hashCode相同将被放在同一个位置
    public int hashCode(){ return 1;  }
}

class C{
    //都覆盖才能被当成同样的对象
    public boolean equals(Object x){ return true;  }
    public int hashCode(){ return 2; }
}

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet demoHs = new HashSet();
        demoHs.add(new A());
        demoHs.add(new A());
        demoHs.add(new B());
        demoHs.add(new B());
        //两个元素equals相同，hashcode又相同，所以没法添加两个对象，只能添加一个
        demoHs.add(new C());
        demoHs.add(new C());
        System.out.println(demoHs);

        System.out.println("===========");
        HashSet<Ele> hes = new HashSet<Ele>();
        Ele ele1 = new Ele("good");
        Ele ele2 = new Ele("bad");
        System.out.println("equals?" + ele1.equals(ele2));
        hes.add(ele1);
        hes.add(ele2);
        System.out.println(hes);

        System.out.println("===========");
        HashSet<String> hs = new HashSet<String>();
        hs.add("Hello");
        hs.add("Hello");
        System.out.println(hs);
    }
}

class Ele {
    String name;

    public Ele(String value) {
        name = value;
    }

    public boolean equals(Ele anotherEle) {
        return true;
    }

    public String toString() {
        return name;
    }

}

